<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use OSS\OssClient;
use OSS\Core\OssException;
use org\Qiniu;
use Qiniu\Processing\PersistentFop;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已被删除';
    // 构造函数
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
//        return 112;
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 2111;
            }
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                return 111;
            }
        }
    }
    
    /**
     * 用户权限
     * @return mixed
     * 1 点即丽（即普通用户）   2 特惠商品   3 脖脸皮    2,3  特惠商品&脖脸皮
     */
    public function userRule($userid){
        $user_rule = Db::table('up_u_user')->where('user_id', $userid)->value('user_rule');
        return $user_rule;
    }
    
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json_encode(array('data'=>$token));
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $SpCode = '230149';
        $LoginName = 'js_px';
        $Password = 'panson58398860';
        $MessageContent = iconv("UTF-8", "gbk//TRANSLIT", "您的验证码为{$num}，请在10分钟内使用！");
        $body = "SpCode=$SpCode&LoginName=$LoginName&Password=$Password&MessageContent=$MessageContent&UserNumber=$phone&SerialNumber=&ScheduleTime=&f=1";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $url = 'https://api.ums86.com:9600/sms/Api/Send.do';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = mb_convert_encoding($result,'UTF-8','GBk');
        $res = explode('&',$result);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json_encode(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
    function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        // 重复的号
        $rep = Db::table('up_u_user')->where('user_invite', $char_txt)->find();
        if($rep){
            $char_txt = $this->getRandChar($length);
        }
        return $char_txt;
    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        $push->options(array(
            // apns_production: 表示APNs是否生产环境，
            // true 表示推送生产环境，false 表示要推送开发环境；如果不指定则默认为推送生产环境
            'apns_production' => false,
        ));
        return $push->send();
    }
    
    /**
     * 生成二维码
     * @param $invite_other      我的邀请码
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function getQrcode($invite_code, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
        $value = $invite_code;
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/inviteQrcode';
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $invite_code . '_' . date('YmdHis') . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/inviteQrcode/' . $invite_code . '_' . date('YmdHis') . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }
    
    /**
     * 生成私人订制订单二维码
     * @param $invite_other      订单编号
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function getOrderQrcode($order_number, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
        $val = 'http://share.djlwlsc.com/djl/haibao_frm.html?order_number=' . $order_number;
//        $val = 'http://new4.xuanwumobile.com/djl/haibao_frm.html?order_number=' . $order_number;
        $value = $val;
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/orderQrcode';
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $order_number . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/orderQrcode/' . $order_number . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }
    
    /**
     * 过滤敏感词
     * @param $str    需要过滤的字符串
     * @return array
     */
    public function sensitiveWord($str){
        $sensitive = Db::table('up_sensitive')->column('s_word');
        $return = ['status' => 1, 'msg' => ''];
        if($sensitive){
            foreach($sensitive as $v){
                if(strpos($str, $v) !== false){
                    $return['status'] = 2;
                    $return['msg'] = $v;
                    break;
                }
            }
        }
        return $return;
    }
    
    public function rongyun($uid,$name,$imageurl){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $uid = strval($uid);
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }
    
    /**
     * 音频转码
     * @param $key
     */
    public function audioZhuanma($key){
        set_time_limit (0);
        $bucket = config('qiniu')['bucket'];
        $_Auth = new Qiniu();
        $auth = $_Auth->auth();
        $pipeline = config('qiniu')['pipeline'];//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp3/ab/192k|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'audio_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
        return $res;
    }

    /**
     * 身份证实名认证
     * @param $real_name    真实姓名
     * @param $card         身份证号
     * @return array
     */
    public function checkIdCard($real_name, $card){
        $apiurl = "http://op.juhe.cn/idcard/query";//请求地址
        $key = 'cebc4c6eed7ba0d7df1bc5d99848de1f';//32位的KEY
        $realname = $real_name;//真实姓名
        $idcard = $card;//身份证号码
        $params = compact('key', 'realname', 'idcard');//组合请求参数
        $content = $this->juhecurl($apiurl, $params);//获取接口返回内容json字符串
        $result = json_decode($content, true);//解析成数组
        if($result){
            if($result['error_code'] == 0){
                if($result['result']['res'] == 1){
//                    echo "身份证号码和真实姓名一致";
                    return ['status' => 200, 'msg' => true];
                }else{
//                    echo "身份证号码和真实姓名不一致";
                    return ['status' => 0, 'msg' => '身份证号码和真实姓名不一致'];
                }
                #print_r($result);
            }else{
//                echo $result['error_code'] . ":" . $result['reason'];
                return ['status' => 0, 'msg' => $result['error_code'] . ':' . $result['reason']];
            }
        }else{
            return ['status' => 0, 'msg' => '接口请求失败'];
        }
    }

    /**
     * 请求接口---聚合数据
     * @param $url       请求地址
     * @param $params    参数
     * @param $ispost    请求方式和
     * @return bool|string
     */
    function juhecurl($url, $params = false, $ispost = 0){
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 8);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($params) {
            if (is_array($params)) {
                $paramsString = http_build_query($params);
            } else {
                $paramsString = $params;
            }
        } else {
            $paramsString = "";
        }
        if($ispost)
        {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsString);
            curl_setopt($ch, CURLOPT_URL, $url);
        }
        else
        {
            if($paramsString){
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $paramsString);
            }else{
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

    /**
     * 判断当天是否在可提现日期内
     * @return array
     */
    public function canTxDate(){
        $can = 1; // 可提现
        $date = Db::table('up_bo_fy_config')->where('bfc_id', 9)->value('bfc_content');
        $dateRange = str_replace('，', ',', $date);
        $dateRange = trim($dateRange, ',');
        $today = date('d');
        $dateArr = explode(',', $dateRange);
        if(!in_array($today, $dateArr)){
            $can = 2; // 不可提现
        }
        return ['can' => $can, 'date' => $dateRange];
    }

    /**
     * 获取补货款分佣信息
     * @param $type      1 本团/上级团长   2 上级/上上级团长
     * @param $role      我的系统身份
     * @param $upTz      本级/上级团队长
     * @param $upUpTz    上级/上上级团队长
     * @return int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBoUserSystemHuo($type, $role, $upTz, $upUpTz){
        $bfc_id = 0;
        $fyUser = [
            'tz_user_id' => 0,
            'should_user_id' => 0,
            'freeze_user_id' => 0,
            'ratio' => 0,
            'bo_balance' => 0,
            'hf' => 2,
            'freeze_name' => ''
        ];

        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 我是团员时，代表本团长；我是团长时代表上级团长
            if($upTz != -1){
                $_selfTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $fyUser['should_user_id'] = $_selfTz['user_id'];
                if($_selfTz['user_teamer_status'] == 2){
                    $fyUser['tz_user_id'] = $companyUser['user_id'];
                    $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fyUser['hf'] = 1;
                    $fyUser['freeze_name'] = $_selfTz['user_real_name'];
                }else{
                    $fyUser['tz_user_id'] = $_selfTz['user_id'];
                    $fyUser['bo_balance'] = $_selfTz['user_bo_fy_balance'];
                }
                if($role == 3){
                    $bfc_id = 32; // 本团团长分佣ID
                }else{
                    $bfc_id = 27; // 上级团长分佣ID
                }
            }
        }else{
            // 我是团员时，代表上级团长；我是团长时代表上上级团长
            if($upUpTz != -1){
                $_selfTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $_upTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upUpTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $fyUser['should_user_id'] = $_upTz['user_id'];
                if($_selfTz['user_teamer_status'] == 2){
                    $fyUser['tz_user_id'] = $companyUser['user_id'];
                    $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fyUser['freeze_user_id'] = $_selfTz['user_id'];
                    $fyUser['hf'] = 1;
                    $fyUser['freeze_name'] = $_selfTz['user_real_name'];
                }else{
                    if($_upTz['user_teamer_status'] == 2){
                        $fyUser['tz_user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_name'] = $_upTz['user_real_name'];
                    }else{
                        $fyUser['tz_user_id'] = $_upTz['user_id'];
                        $fyUser['bo_balance'] = $_upTz['user_bo_fy_balance'];
                    }
                }
                if($role == 3){
                    $bfc_id = 33; // 上级团长分佣ID
                }else{
                    $bfc_id = 28; // 上上级团长分佣ID
                }
            }
        }

        if($bfc_id != 0){
            $ratio = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
            $fyUser['ratio'] = $ratio;
        }

        return $fyUser;
    }

    /**
     * 地区代理管理费
     * @param $type      1 省代   2 市代  3 县代
     * @param $district  地区ID
     * @return array|\int[][]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDaiLiFy($type, $district){
        $fy = [
            'fy_user_id' => 0,
            'should_user_id' => 0,
            'ratio' => 0,
            'bo_balance' => 0,
            'hf' => 2,
            'freeze_name' => ''
        ];

        $bfc_id = 0; // 分佣比例

        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 省代
            $provinceDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,4,%'], 'user_agency_sheng' => $district])
                ->field('user_id, user_agency_sheng_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($provinceDaiLi){
                $bfc_id = 31;
                $fy['should_user_id'] = $provinceDaiLi['user_id'];
                if($provinceDaiLi['user_agency_sheng_status'] == 1){
                    $fy['fy_user_id'] = $provinceDaiLi['user_id'];
                    $fy['bo_balance'] = $provinceDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $provinceDaiLi['user_real_name'];
                }
            }
        }elseif ($type == 2){
            // 市代
            $cityDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,3,%'], 'user_agency_shi' => $district])
                ->field('user_id, user_agency_shi_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($cityDaiLi){
                $bfc_id = 30;
                $fy['should_user_id'] = $cityDaiLi['user_id'];
                if($cityDaiLi['user_agency_shi_status'] == 1){
                    $fy['fy_user_id'] = $cityDaiLi['user_id'];
                    $fy['bo_balance'] = $cityDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $cityDaiLi['user_real_name'];
                }
            }
        }else{
            // 县代
            $districtDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,2,%'], 'user_agency_qu' => $district])
                ->field('user_id, user_agency_qu_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($districtDaiLi){
                $bfc_id = 29;
                $fy['should_user_id'] = $districtDaiLi['user_id'];
                if($districtDaiLi['user_agency_qu_status'] == 1){
                    $fy['fy_user_id'] = $districtDaiLi['user_id'];
                    $fy['bo_balance'] = $districtDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $districtDaiLi['user_real_name'];
                }
            }
        }
        if($bfc_id != 0){
            $fy['ratio'] = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
        }
        return $fy;
    }

    /*
     * 获取第一个未被使用过的团长编号
     * @return array|bool|PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFirstNoUseTzCode(){
        // 第一个未被使用的编号
        $code = Db::table('up_bo_team_code')->field('id, code')->where('is_use', 1)->order('id asc')->find();
        // 用完之后要把该编码改成已使用
        Db::table('up_bo_team_code')->where('id', $code['id'])->setField('is_use', 2);
        return $code;
    }

    /*
     * 获取某个团队的团员编号
     * @param $tzCode    团长编号
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTyCode($tzCode){
        $code = Db::table('up_u_user')
            ->where('user_up_tz_code', $tzCode)
            ->field('user_ty_code')
            ->order('user_ty_code desc')
            ->find();
        if(!$code){
            $code['user_ty_code'] = 0;
        }
        return $code;
    }

    /*
     * 获取上级邀请的团员或者团长的数量
     * @param $user_invite   上级邀请码
     * @return int|string
     * @throws \think\Exception
     */
    public function getLowerNumber($user_invite){
        $number = Db::table('up_u_user')
            ->where([
                'user_bo_invite_other' => $user_invite,
                'user_bo_role' => ['>', 2],
            ])
            ->count();
        return $number;
    }

    /**
     * 插入脖脸皮积分表
     * @param $user_id            用户ID
     * @param $type               积分类型     1 积分获取   2 积分支出
     * @param $desc               积分描述
     * @param $balance            积分数量
     * @param $user_balance       用户现有积分
     * @param $order_id           订单ID
     */
    public function insertBoInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $order_number = 'BI_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte_id = Db::table('up_bo_integral')
            ->insertGetId([
                'binte_user_id'        => $user_id,
                'binte_number'         => $order_number,
                'binte_type'           => $type,
                'binte_desc'           => $desc,
                'binte_price'          => $balance,
                'binte_front'          => $user_balance,
                'binte_after'          => $after,
                'binte_order_id'       => $order_id,
                'binte_time'           => date('Y-m-d H:i:s'),
                'binte_admin_id'       => ''
            ]);
        return $inte_id;
    }

    /**
     * 插入脖脸皮分佣表
     * @param $user_id            实际获取佣金用户ID
     * @param $other_user_id      佣金产生着ID
     * @param $should_user_id     应该获取佣金用户ID
     * @param $freeze_user_id     因为谁被冻结了，导致我的分佣也被冻结
     * @param $type               佣金类型     1 佣金获取   2 佣金支出
     * @param $desc               描述
     * @param $cate               1 分佣   2 提现到银行卡    3 提现到积分  4 提现拒绝退回
     * @param $balance            佣金数量
     * @param $user_balance       用户现有佣金
     * @param $order_id           订单ID
     * @param $hf                 是否需要恢复      1 未恢复/需要恢复   2 已恢复/不需要恢复
     * @param $tc_from            提成来源  1 团队长提成   2 县代提成  3 市代提成  4 省代提成
     * @param $freeze_name        提成来源  是谁冻结了，导致分佣进了公司账户
     * @return int|string
     */
    public function insertBoFy($user_id = 0, $other_user_id = 0, $should_user_id = 0, $freeze_user_id = 0,
                               $type = 1, $desc = '', $cate = 1, $balance = 0, $user_balance = 0,
                               $order_id = 0, $hf = 2, $tc_from = 0, $freeze_name = ''){
        $order_number = 'BF_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte_id = Db::table('up_bo_fy')
            ->insertGetId([
                'binte_user_id'        => $user_id,
                'binte_other_user_id'  => $other_user_id,
                'binte_number'         => $order_number,
                'binte_type'           => $type,
                'binte_desc'           => $desc,
                'binte_price'          => $balance,
                'binte_front'          => $user_balance,
                'binte_after'          => $after,
                'binte_order_id'       => $order_id,
                'binte_time'           => date('Y-m-d H:i:s'),
                'binte_cate'           => $cate,
                'binte_should_user_id' => $should_user_id,
                'binte_freeze_user_id' => $freeze_user_id,
                'binte_from'           => $tc_from,
                'binte_hf'             => $hf,
                'binte_admin_id'       => '',
                'binte_freeze_name'    => $freeze_name
            ]);
        return $inte_id;
    }

    /**
     * 特惠商品积分明细
     * @param $user_id       用户ID
     * @param $type          1 充值   2 支出
     * @param $desc          描述
     * @param $balance       积分
     * @param $user_balance  用户充值钱可用积分
     * @param $order_id      订单ID
     * @return int|string
     */
    public function insertThInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $num = 'THJF_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte = [
            'inte_user_id' => $user_id,
            'inte_num' => $num,
            'inte_type' => $type,
            'inte_des' => $desc,
            'inte_number' => $balance,
            'inte_front' => $user_balance,
            'inte_after' => $after,
            'inte_order_num' => $order_id,
            'inte_time' => date('Y-m-d H:i:s'),
            'inte_admin' => ''
        ];
        $inte_id = Db::table('up_integral')->insertGetId($inte);
        return $inte_id;
    }

    /**
     * 家大业大积分明细
     * @param $user_id       用户ID
     * @param $type          1 充值   2 支出
     * @param $desc          描述
     * @param $balance       积分
     * @param $user_balance  用户充值前可用积分
     * @param $order_id      订单ID
     * @return int|string
     */
    public function insertBigInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $num = 'BIG_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte = [
            'binte_user_id' => $user_id,
            'binte_number' => $num,
            'binte_type' => $type,
            'binte_desc' => $desc,
            'binte_price' => $balance,
            'binte_front' => $user_balance,
            'binte_after' => $after,
            'binte_order_id' => $order_id,
            'binte_time' => date('Y-m-d H:i:s'),
            'binte_admin_id' => ''
        ];
        $inte_id = Db::table('up_big_integral')->insertGetId($inte);
        return $inte_id;
    }

    /**
     * 获取脖脸皮充值系统分佣---首批款----作废
     * @param $rechargeType      充值类型    1 首批款直开   2 首批款团长
     * @param $upXie             直开协助    1 有    2 无
     * @param $tzXie             团长协助    1 有    2 无
     * @param $qd                渠道        1 线上    2 线下
     * @return int|mixed
     */
    public function getBoUserSystemFirstRatio($rechargeType, $upXie = 0, $tzXie = 0, $qd = 0){
        $bfc_id = 0;
        if($rechargeType == 1){
            if($qd == 1){
                if($upXie == 1){
                    $bfc_id = 20;
                }else{
                    $bfc_id = 19;
                }
            }else{
                if($upXie == 1){
                    $bfc_id = 24;
                }else{
                    $bfc_id = 23;
                }
            }
        }else{
            if($qd == 1){
                if($tzXie == 1){
                    $bfc_id = 21;
                }else{
                    $bfc_id = 22;
                }
            }else{
                if($tzXie == 1){
                    $bfc_id = 25;
                }else{
                    $bfc_id = 26;
                }
            }
        }
        if($bfc_id == 0){
            $ratio = 0;
        }else{
            $ratio = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
        }
        return $ratio;
    }

    /*
     * 获取首批款分佣用户
     * @param $type           1 直开   2 团长
     * @param $upTz           我的本团/上级团长
     * @param $upUpTz         上级团长/上上级团长
     * @param $up             上级
     * @return array|int[][]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFirstFyUser($type, $upTz, $upUpTz, $up){
        $fyUser = [
            'user_id' => 0,
            'should_user_id' => 0,
            'freeze_user_id' => 0,
            'bo_balance' => 0,
            'up_role' => 0,
            'hf' => 2,
            'freeze_name' => ''
        ];
        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 直开分佣
            $fyUser['user_id'] = $up['user_id'];
            $fyUser['should_user_id'] = $up['user_id'];
            $fyUser['bo_balance'] = $up['user_bo_fy_balance'];
            $fyUser['up_role'] = $up['user_bo_role'];
            if($up['user_bo_role'] == 4 && $up['user_teamer_status'] == 2){ // 上级是团长并且被冻结
                $fyUser['user_id'] = $companyUser['user_id'];
                $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                $fyUser['hf'] = 1;
                $fyUser['freeze_name'] = $up['user_real_name'];
            }
        }else{
            // 团长分佣，如果直开是团员，则需要分给我所在团的团长
            if($up['user_bo_role'] == 3){
                if($upTz != -1){
                    $upTzUser = Db::table('up_u_user')
                        ->where('user_tz_code', $upTz)
                        ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                        ->find();
                    $fyUser['should_user_id'] = $upTzUser['user_id'];
                    if($upTzUser['user_teamer_status'] == 2){
                        $fyUser['user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_name'] = $upTzUser['user_real_name'];
                    }else{
                        $fyUser['user_id'] = $upTzUser['user_id'];
                        $fyUser['bo_balance'] = $upTzUser['user_bo_fy_balance'];
                    }
                }

            }else{
                if($upUpTz != -1){
                    $upUpTzUser = Db::table('up_u_user')
                        ->where('user_tz_code', $upUpTz)
                        ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                        ->find();

                    $fyUser['should_user_id'] = $upUpTzUser['user_id'];

                    if($up['user_teamer_status'] == 2){
                        $fyUser['user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_user_id'] = $up['user_id'];
                        $fyUser['freeze_name'] = $up['user_real_name'];
                    }else{
                        if($upUpTzUser['user_teamer_status'] == 2){
                            $fyUser['user_id'] = $companyUser['user_id'];
                            $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                            $fyUser['hf'] = 1;
                            $fyUser['freeze_name'] = $upUpTzUser['user_real_name'];
                        }else{
                            $fyUser['user_id'] = $upUpTzUser['user_id'];
                            $fyUser['bo_balance'] = $upUpTzUser['user_bo_fy_balance'];
                        }
                    }
                }

            }
        }

        return $fyUser;
    }

    public function aaaa(){
        $num = '';
        $thirdNumber = '';
        $order = Db::table('up_shou')
            ->where('shou_number', $num)
            ->field([
                'shou_id',
                'shou_is_pay',
                'shou_user_id',
                'shou_project_id',
                'shou_remark',
                'shou_price'
            ])
            ->find();
        if($order['shou_is_pay'] == 1){

            $user = Db::table('up_u_user')
                ->where('user_id', $order['shou_user_id'])
                ->field([
                    'user_invite',
                    'user_bo_invite_other',
                    'user_bo_role',
                    'user_recharge_price',
                    'user_bo_balance',
                    'user_real_name',
                    'user_up_tz_code',
                    'user_up_up_tz_code',
                    'user_sheng',
                    'user_shi',
                    'user_qu',
                    'user_recharge_balance',
                    'user_big_balance'
                ])
                ->find();

            $upUser = Db::table('up_u_user')
                ->where('user_invite', $user['user_bo_invite_other'])
                ->field([
                    'user_bo_role',
                    'user_up_tz_code',
                    'user_up_up_tz_code',
                    'user_tz_code',
                    'user_invite',
                    'user_id',
                    'user_bo_fy_balance',
                    'user_teamer_status',
                    'user_real_name'
                ])
                ->find();
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_shou')->where('shou_id', $order['shou_id'])
                    ->update([
                        'shou_other_number' => $thirdNumber,
                        'shou_is_pay' => 2,
                        'shou_pay_time' => date('Y-m-d H:i:s')
                    ]);

                /**
                 * 1.首批款：变更身份，首批款积分，分佣
                 * 2.补货款：补货款积分，分佣，管理费
                 * 3.活动诚意金：不入积分（已取消此充值款项）
                 * 4.特惠商品：特惠商品积分
                 * 5.家大业大：家大业大积分
                 * 6.其它：不计入积分，只需要支付记录
                 * 7.定金：其它款项积分，不分佣
                 *
                 */
                if($order['shou_project_id'] == 1){
                    //*********************************   变更我的身份  start  ********************//
                    if($order['shou_price'] == 19800){
                        $boRole = 3; // 团员
                    }else{
                        $boRole = 4; // 团长
                    }

                    if($upUser['user_bo_role'] == 3){ // 如果上级是团员
                        $upTz = $upUser['user_up_tz_code'];
                        $upUpTz = $upUser['user_up_up_tz_code'];
                    }else{
                        $upTz = $upUser['user_tz_code'];
                        $upUpTz = $upUser['user_up_tz_code'];
                    }
                    if($boRole == 3){ // 团员
                        $tzCode = -1; // 团队长编号
                    }else{ // 团长
                        // 第一个未被使用的编号
                        $code = $this->getFirstNoUseTzCode();
                        $tzCode = $code['code']; // 团队长编号
                    }
                    $_ty = $this->getTyCode($upTz);
                    $tyCode = $_ty['user_ty_code'] + 1; // 团员编号

                    $updateUser = [
                        'user_id' => $order['shou_user_id'],
                        'user_bo_role' => $boRole,
                        'user_tz_code' => $tzCode,
                        'user_ty_code' => $tyCode,
                        'user_up_tz_code' => $upTz,
                        'user_up_up_tz_code' => $upUpTz,
                        'user_recharge_price' => $order['shou_price'],
                        'user_is_recharge' => 1,
                        'user_update_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_u_user')->update($updateUser);

                    //******************************  变更上级身份
                    // 如果上级不是团长，并且推广了两个团员，则可以升级成团长
                    $lowerCount = $this->getLowerNumber($upUser['user_invite']);
                    if($upUser['user_bo_role'] != 4 && $lowerCount == 2){
                        // 第一个未被使用的编号
                        $upCode = $this->getFirstNoUseTzCode();
                        $upTzCode = $upCode['code']; // 上级团队长编号

                        $upUserUpdate = [
                            'user_id' => $upUser['user_id'],
                            'user_bo_role' => 4,
                            'user_tz_code' => $upTzCode,
                            'user_update_time' => date('Y-m-d H:i:s')
                        ];
                        Db::table('up_u_user')->update($upUserUpdate);
                    }
                    //*********************************   变更我的身份  end  ********************//

                    //*********************************   首批款充值   start ********************//
                    // 1.用户积分
                    if($order['shou_remark']){
                        $descFirst = '首批款-' . $order['shou_remark'];
                    }else{
                        $descFirst = '首批款';
                    }
                    $this->insertBoInte($order['shou_user_id'], 1, $descFirst, $order['shou_price'], $user['user_bo_balance'], 0);

                    Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->inc('user_bo_total_balance', $order['shou_price'])
                        ->inc('user_bo_balance', $order['shou_price'])
                        ->inc('user_bo_first_balance', $order['shou_price'])
                        ->update();

                    //*********************************   首批款充值   end ********************//

                    //*********************************   首批款分佣   start ********************//
                    // 2.直开分佣
//                            $firstUpRatio = $this->getBoUserSystemFirstRatio(1, $zk, 0, $qd); // 提点比例
                    $firstUpRatio = config('default_first_up_ratio'); // 提点比例
                    $firstUpFy = $order['shou_price'] * $firstUpRatio / 100; // 分佣金额

                    $userFirst = Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->field([
                            'user_up_tz_code',
                            'user_up_up_tz_code',
                            'user_real_name'
                        ])
                        ->find();

                    // 直开&团长信息
                    $upFyUser = $this->getFirstFyUser(1, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($upFyUser);
                    if($upFyUser['up_role'] == 4){
                        $firstFyFrom = 1;
                    }else{
                        $firstFyFrom = 0;
                    }
                    $firstUpDesc = $user['user_real_name'] . '首批款-佣金';
                    $this->insertBoFy($upFyUser['user_id'], $order['shou_user_id'], $upFyUser['should_user_id'], $upFyUser['freeze_user_id'], 1, $firstUpDesc, 1, $firstUpFy, $upUser['user_bo_fy_balance'], 0, $upFyUser['hf'], $firstFyFrom, $upFyUser['freeze_name']);

                    Db::table('up_u_user')
                        ->where('user_id', $upFyUser['user_id'])
                        ->inc('user_bo_fy_balance', $firstUpFy)
                        ->inc('user_bo_total_fy_balance', $firstUpFy)
                        ->update();


                    // 3.团长分佣
                    $tzFyUser = $this->getFirstFyUser(2, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($tzFyUser);die;
                    if($tzFyUser['should_user_id'] != 0){
//                                $firstTzRatio = $this->getBoUserSystemFirstRatio(2, 0, $tz, $qd); // 提点比例
                        $firstTzRatio = config('default_first_tz_ratio'); // 提点比例
                        $firstTzFy = $order['shou_price'] * $firstTzRatio / 100; // 分佣金额
                        $firstTzDesc = $userFirst['user_real_name'] . '首批款-佣金';

                        $this->insertBoFy($tzFyUser['user_id'], $order['shou_user_id'], $tzFyUser['should_user_id'], $tzFyUser['freeze_user_id'], 1, $firstTzDesc, 1, $firstTzFy, $tzFyUser['bo_balance'], 0, $tzFyUser['hf'], 1, $tzFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $tzFyUser['user_id'])
                            ->inc('user_bo_fy_balance', $firstTzFy)
                            ->inc('user_bo_total_fy_balance', $firstTzFy)
                            ->update();
                    }
                    //*********************************   首批款分佣   end ********************//

                }elseif ($order['shou_project_id'] == 2){
                    //*************************  补货款充值   start ****************************//
                    // 1.用户补货款
                    if($order['shou_remark']){
                        $descHuo = '补货款-' . $order['shou_remark'];
                    }else{
                        $descHuo = '补货款';
                    }

                    $this->insertBoInte($order['shou_user_id'], 1, $descHuo, $order['shou_price'], $user['user_bo_balance'], 0);

                    // 用户积分
                    Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->inc('user_bo_total_balance', $order['shou_price'])
                        ->inc('user_bo_balance', $order['shou_price'])
                        ->inc('user_bo_huo_balance', $order['shou_price'])
                        ->update();
                    //*************************  补货款充值   end ****************************//

                    //*************************  团长分佣   start ****************************//
                    // 2.本团/上级分佣
                    $upHuoFyUser = $this->getBoUserSystemHuo(1, $user['user_bo_role'], $user['user_up_tz_code'], $user['user_up_up_tz_code']);
                    if($upHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
                        $huoTzFy1 = $order['shou_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                        $descFyHuo1 = $user['user_real_name'] . '补货款-佣金';

                        $this->insertBoFy($upHuoFyUser['tz_user_id'], $order['shou_user_id'], $upHuoFyUser['should_user_id'], $upHuoFyUser['freeze_user_id'], 1, $descFyHuo1, 1, $huoTzFy1, $upHuoFyUser['bo_balance'], 0, $upHuoFyUser['hf'], 1, $upHuoFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $upHuoFyUser['tz_user_id'])
                            ->inc('user_bo_fy_balance', $huoTzFy1)
                            ->inc('user_bo_total_fy_balance', $huoTzFy1)
                            ->update();
                    }

                    // 3.上级/上上级团队长分佣
                    $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $user['user_bo_role'], $user['user_up_tz_code'], $user['user_up_up_tz_code']);
                    if($upUpHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
                        $huoTzFy2 = $order['shou_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                        $descFyHuo2 = $user['user_real_name'] . '补货款-佣金';

                        $this->insertBoFy($upUpHuoFyUser['tz_user_id'], $order['shou_user_id'], $upUpHuoFyUser['should_user_id'], $upUpHuoFyUser['freeze_user_id'], 1, $descFyHuo2, 1, $huoTzFy2, $upUpHuoFyUser['bo_balance'], 0, $upUpHuoFyUser['hf'], 1, $upUpHuoFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $upUpHuoFyUser['tz_user_id'])
                            ->inc('user_bo_fy_balance', $huoTzFy2)
                            ->inc('user_bo_total_fy_balance', $huoTzFy2)
                            ->update();
                    }
                    //*************************  团长分佣   end ****************************//

                    //*************************  代理分佣   start ****************************//
                    // 4.县代管理费
                    $quFyUser = $this->getDaiLiFy(3, $user['user_qu']);
                    if($quFyUser['should_user_id'] != 0){
//                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
                        $huoDlFy3 = $order['shou_price'] * config('default_qu_ratio') / 100; // 分佣金额
                        $descFyHuo3_dl = $user['user_real_name'] . '补货款-县管理费';

                        $this->insertBoFy($quFyUser['fy_user_id'], $order['shou_user_id'], $quFyUser['should_user_id'], 0, 1, $descFyHuo3_dl, 1, $huoDlFy3, $quFyUser['bo_balance'], 0, $quFyUser['hf'], 2, $quFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $quFyUser['fy_user_id'])
                            ->inc('user_bo_fy_balance', $huoDlFy3)
                            ->inc('user_bo_total_fy_balance', $huoDlFy3)
                            ->update();
                    }

                    // 5.市代管理费
                    $shiFyUser = $this->getDaiLiFy(2, $user['user_shi']);
                    if($shiFyUser['should_user_id'] != 0){
//                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
                        $huoDlFy2 = $order['shou_price'] * config('default_shi_ratio') / 100; // 分佣金额
                        $descFyHuo2_dl = $user['user_real_name'] . '补货款-市管理费';

                        $this->insertBoFy($shiFyUser['fy_user_id'], $order['shou_user_id'], $shiFyUser['should_user_id'], 0, 1, $descFyHuo2_dl, 1, $huoDlFy2, $shiFyUser['bo_balance'], 0, $shiFyUser['hf'], 3, $shiFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $shiFyUser['fy_user_id'])
                            ->inc('user_bo_fy_balance', $huoDlFy2)
                            ->inc('user_bo_total_fy_balance', $huoDlFy2)
                            ->update();
                    }

                    // 6.省代管理费
                    $shengFyUser = $this->getDaiLiFy(1, $user['user_sheng']);
                    if($shengFyUser['should_user_id'] != 0){
//                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
                        $huoDlFy1 = $order['shou_price'] * config('default_sheng_ratio') / 100; // 分佣金额
                        $descFyHuo1_dl = $user['user_real_name'] . '补货款-省管理费';

                        $this->insertBoFy($shengFyUser['fy_user_id'], $order['shou_user_id'], $shengFyUser['should_user_id'], 0, 1, $descFyHuo1_dl, 1, $huoDlFy1, $shengFyUser['bo_balance'], 0, $shengFyUser['hf'], 4, $shengFyUser['freeze_name']);

                        Db::table('up_u_user')
                            ->where('user_id', $shengFyUser['fy_user_id'])
                            ->inc('user_bo_fy_balance', $huoDlFy1)
                            ->inc('user_bo_total_fy_balance', $huoDlFy1)
                            ->update();
                    }
                    //*************************  代理分佣   end ****************************//
                }elseif ($order['shou_project_id'] == 3){
                    // TODO:暂时没有该充值项
                }elseif ($order['shou_project_id'] == 4){
                    //******************  特惠商品充值（不参与分佣）   start   **********************//
                    if($order['shou_remark']){
                        $desc_ms = '特惠商品款-' . $order['shou_remark'];
                    }else{
                        $desc_ms = '特惠商品款';
                    }

                    // 用户积分明细
                    $this->insertThInte($order['shou_user_id'], 1, $desc_ms, $order['shou_price'], $user['user_recharge_balance'], 0);

                    // 用户积分
                    Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->inc('user_total_balance', $order['shou_price'])
                        ->inc('user_recharge_balance', $order['shou_price'])
                        ->update();
                    //******************  特惠商品充值（不参与分佣）   end   **********************//
                }elseif ($order['shou_project_id'] == 5){
                    // TODO: 家大业大积分
                    //******************  家大业大充值（不参与分佣）   start   **********************//
                    if($order['shou_remark']){
                        $desc_big = '家大业大款-' . $order['shou_remark'];
                    }else{
                        $desc_big = '家大业大款';
                    }

                    // 用户积分明细
                    $this->insertBigInte($order['shou_user_id'], 1, $desc_big, $order['shou_price'], $user['user_big_balance'], 0);

                    // 用户积分
                    Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->inc('user_big_total_balance', $order['shou_price'])
                        ->inc('user_big_balance', $order['shou_price'])
//                                ->inc('user_recharge_balance', $order['shou_price'])
                        ->update();
                    //******************  家大业大充值（不参与分佣）   end   **********************//
                }elseif ($order['shou_project_id'] == 6){
                    // TODO:不计入积分
                }elseif ($order['shou_project_id'] == 7){
                    //*************************  定金充值 （不参与分佣，充入其它款项）  start ****************************//
                    if($order['shou_remark']){
                        $descD = '定金-' . $order['shou_remark'];
                    }else{
                        $descD = '定金';
                    }

                    $this->insertBoInte($order['shou_user_id'], 1, $descD, $order['shou_price'], $user['user_bo_balance'], 0);

                    // 用户积分
                    Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->inc('user_bo_total_balance', $order['shou_price'])
                        ->inc('user_bo_balance', $order['shou_price'])
                        ->inc('user_bo_other_balance', $order['shou_price'])
                        ->update();
                    //*************************  定金充值 （不参与分佣，充入其它款项）   end ****************************//
                }

                Db::commit();
                $result = true;
            }catch (\Exception $e){
                Db::rollback();
                $result = false;
            }
        }else{
            $result = true;
        }
    }
    
}